<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()" ref="dataForm">
      <el-form-item prop="noticeName">
        <el-input v-model="dataForm.iconName" placeholder="请输入图标名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="search()">查询</el-button>
        <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%;"
    >
      <el-table-column prop="iconName" header-align="center" align="center" label="图标名称"></el-table-column>
      <el-table-column header-align="center" align="center" label="图标">
        <template slot-scope="scope">
          <img style="width: 50px;height: 50px;" :src="scope.row.iconUrl" alt="">
        </template>
      </el-table-column>
      <el-table-column prop="gmtCreate" header-align="center" align="center" label="创建时间"></el-table-column>
      <el-table-column prop="gmtUpdated" header-align="center" align="center" label="更新时间"></el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <el-dialog
      :title="!form.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >
      <el-form
        :model="form"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="150px"
      >
        <el-form-item label="图标名称">
          <el-input v-model="form.iconName"></el-input>
        </el-form-item>
        <el-form-item label="上传图标">
          <el-upload
            :action="url"
            list-type="picture-card"
            :before-upload="handlePictureCardPreview"
            :on-success="PictureCardPreview"
            :file-list="fileLists"
            :on-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

  export default {
    data() {
      return {
        visible: false,
        steward: [],
        useroption: [
          {
            value: "1",
            label: "推送"
          },
          {
            value: "0",
            label: "不推送"
          }
        ],
        dataForm: {
          id: "",
          noticeName: "",
          terminalPushState: ""
        },
        forbidState: "",

        isAlive: "",
        dataList: [],
        fileLists: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        form: {},
        url: ''
      };
    },
    mounted() {
      this.getDataList();
      this.url = this.$http.adornUrl(
        `/operate/shareInfo/upload?token=${this.$cookie.get('token')}`
      )
    },
    methods: {
      search() {
        this.pageIndex = 1;
        this.getDataList();
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true;
        var obj = {
          page: this.pageIndex,
          limit: this.pageSize
        };
        if (this.dataForm.iconName) {
          obj.iconName = this.dataForm.iconName;
        }
        this.$http({
          url: this.$http.adornUrl("/user/notice/icon/list"),
          method: "get",
          params: this.$http.adornParams(obj)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list;
            this.totalPage = data.page.totalCount;
          } else {
            this.dataList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
        });
      },
      handlePictureCardPreview: function (file) {
        const isJPG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif'
        if (!isJPG) {
          this.$message.error('上传封面只能是图片!')
        }
        // const isSize = new Promise(function (resolve, reject) {
        //   let size = 88 * 88
        //   let _URL = window.URL || window.webkitURL
        //   let img = new Image()
        //   img.onload = function () {
        //     let valid = size >= file.size
        //     valid ? resolve() : reject()
        //     // resolve()
        //   }
        //   img.src = _URL.createObjectURL(file)
        // }).then(
        //   () => {
        //     return file
        //   },
        //   () => {
        //     this.$message.error('上传到尺寸需为88*88!')
        //     return Promise.reject()
        //   }
        // );
        // return isJPG && isSize
        return isJPG
      },
      PictureCardPreview(response, file, fileList) {
        if (response && response.code === 0) {
          this.fileLists = fileList
          this.form.iconUrl = response.url
        } else {
          return this.$message.error(response.msg)
        }
      },
      beforeRemove(file, fileList) {
        this.fileLists = fileList
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.getDataList();
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val;
        this.getDataList();
      },
      // 新增 / 修改
      addOrUpdateHandle(data) {
        if(data) {
          this.form.id = data.id
          this.form.iconName = data.iconName
          this.form.iconUrl = data.iconUrl
          this.fileLists = [{name:1, url:data.iconUrl}]
        } else {
          this.form.id = ''
          this.form.iconName = ''
          this.form.iconUrl = ''
          this.fileLists = []
        }
        this.$nextTick(()=> {
          this.visible = true;
        })
      },
      // 删除
      deleteHandle(id) {
        this.$confirm(
          `确定删除?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          this.$http({
            url: this.$http.adornUrl("/user/notice/icon/delete"),
            method: "DELETE",
            data: this.$http.adornData({id:id})
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 100,
                onClose: () => {
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          })
        })
      },
      handleExceed(files, fileList) {
        this.$message.warning(`只能上传一张图片`);
      },
      dataFormSubmit() {
        if (!this.form.iconName) {
          this.$message.warning(`请输入图标名称`);
          return false
        }
        if (!this.form.iconUrl) {
          this.$message.warning(`请上传图标`);
          return false
        }
        if (this.form.id) {
          this.$http({
            url: this.$http.adornUrl("/user/notice/icon/update"),
            method: "put",
            data: this.$http.adornData(this.form)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 100,
                onClose: () => {
                  this.visible = false;
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          })
        } else {
          this.$http({
            url: this.$http.adornUrl("/user/notice/icon/save"),
            method: "post",
            data: this.$http.adornData(this.form)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 100,
                onClose: () => {
                  this.visible = false;
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          })
        }
      }
    }
  };
</script>


